<template>
    <div >
        <van-field v-model="text" v-bind="$attrs" readonly is-link :name="name" :label="label" @click="show = !show"></van-field>
        <van-popup :show="show" round position="bottom">
            <van-picker
                    ref="pickRef"
                    :columns="columns"
                    :columns-field-names="customFieldName"
                    show-toolbar
                    v-model="code"
                    value-key="value"
                    :title="$attrs.label"
                    @cancel="show = !show"
                    @confirm="onConfirm"
            ></van-picker>
        </van-popup>
    </div>
</template>

<script setup>
    import { ref,toRefs, defineProps,onMounted,watch,reactive,nextTick,defineEmits } from 'vue';
    const emit = defineEmits(['update:modelValue'])
    const props = defineProps({
//子组件接收父组件传递过来的值
        columns: {
            type:Array // option中的数据
        },
        label:String, // 标题
        modelValue:String, // 绑定的值
        customFieldName:{  // option中数据中对应的name和code的字段名
            type:Object,
            default:{
                text: 'text',
                value: 'value',
            }
        },
        name:String,
    })
    //使用父组件传递过来的值
    const {info} = toRefs(props)
    let pickRef = ref()



    let show = ref(false)
    let text = ref('')
    let code = ref([''])
    const onConfirm = ({ selectedOptions }) => {
        // text.value = selectedOptions[0].text;
        // code.value = selectedOptions[0].value;
        // text.value = selectedOptions[0][props.customFieldName.text];
        // code.value = selectedOptions[0][props.customFieldName.value];
        show.value = !show.value;
    }

    const reShow = () => {
        if(props.modelValue) {
            props.columns.forEach(res => {
                if (res[props.customFieldName.value] == props.modelValue) {
                    text.value = res[props.customFieldName.text];
                }
            })
        }
    }

    watch(()=>code.value,(newVal, oldVal) => {
        // emit('update:modelValue', newVal);
    })

    watch(()=>props.columns,(newVal,oldVal)=>{
        //处理异步数据回显
        reShow();
    })

    watch(()=>props.modelValue,(newVal,oldVal)=>{
        //处理异步数据回显
        reShow();
    })
    onMounted(()=>{
        code.value[0] = props.modelValue
        nextTick(()=>{
            reShow();

        })
        // setTimeout(()=>{
        //     console.log("pickRef.value",pickRef)
        //     pickRef.value.setColumnIndex(0, 3);
        // },3000)
    })
</script>
